package com.yl.nettylearning.netty.day12;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;

/**
 * @author yangl
 */
public class MessageServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();

        System.out.println("===============================================");
        System.out.println("服务器接收到的消息：");
        System.out.println("长度：" + len);
        System.out.println("内容：" + new String(content, CharsetUtil.UTF_8));
        System.out.println("服务器接收到的消息数量：" + (++this.count));

        //回复消息
        String response = "大家一起来偶遇。。。";
        int responseLen = response.getBytes("UTF-8").length;
        byte[] responseBytes = response.getBytes("utf-8");

        MessageProtocol protocol = new MessageProtocol();
        protocol.setLen(responseLen);
        protocol.setContent(responseBytes);
        ctx.writeAndFlush(protocol);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(cause.getMessage());
        ctx.close();
    }
}
